'use strict';

var model = require('../../model/permission.js');
var debug = require('debug')('dao_permission_impl');
var appUtils = require('../../common/app_utils.js');
var errInfo = require('../../common/err_info.js');
var md5 = appUtils.md5;
var fout = appUtils.formatOutput;
var ferror = appUtils.formatError;


function DaoImpl() {
	var self = this instanceof DaoImpl ? this : new DaoImpl();
	return self;
}

module.exports = new DaoImpl();
var theProto = DaoImpl.prototype;
/*
{ "name":"vendor_add","code":123,"description":"添加商家"}
*/
theProto.create = function(json) {
	debug('create ', json);

	var item = new model({
		name: json.name,
		description: json.description || '',
		code: json.code
	});

	return item.save()
		.then(function(result) {
			return fout(result);
		}, function(err) {
			if (err.code === 11000) {
				return ferror(__errDuplicate(err.errmsg));
			}
			return ferror(err.code, 'mongodb error: ' + err.errmsg);
		});
};


// json {query:{}}
theProto.read = function(json) {
	return model.find(json.query, json.projection || __defaultProject)
		.exec()
		.then(function(result) {
			return fout(result);
		}, function(err) {
			return ferror(errInfo.E1000, 'mongodb error: ' + err.errmsg);
		});
};

// handle error info
function __errDuplicate(errmsg) {
	var ptnName = /name/g;
	if (ptnName.exec(errmsg)) {
		return errInfo.E2200;
	}
}

var __defaultProject = {
	_id: 0,
	__v: 0,
	updatedAt: 0,
	createdAt: 0,
	// description: 0
};